#include "sliderform.h"
#include "qdebug.h"
#include "ui_sliderform.h"
#include <QMouseEvent>

sliderForm::sliderForm(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::sliderForm)
    ,movestate(false)
    ,currIndex(0.0)
{
    ui->setupUi(this);

    updateProgressBar();
}

sliderForm::~sliderForm()
{
    delete ui;
}

void sliderForm::setProgress(float progress)
{
    currIndex = qBound(0.0f, progress, 1.0f);
    if (!movestate) {
        updateProgressBar();
    }
}

float sliderForm::progress() const
{
    return currIndex;
}

void sliderForm::updateProgressBar()
{
    int width = ui->frame->width();
    int progressWidth = static_cast<int>(width * currIndex);
    ui->process->setGeometry(0, 7, progressWidth, 6);
}

void sliderForm::mousePressEvent(QMouseEvent *event)
{
    if (event->button() == Qt::LeftButton)
    {
        movestate = true;
        QPoint posInFrame = ui->frame->mapFromParent(event->pos());
        float pos = static_cast<float>(posInFrame.x()) / ui->frame->width();
        setProgress(pos);
        emit progressChanged(currIndex);
    }

}

void sliderForm::mouseReleaseEvent(QMouseEvent *event)
{
    if (movestate && event->button() == Qt::LeftButton) {
        movestate = false;
        QPoint posInFrame = ui->frame->mapFromParent(event->pos());
        float pos = static_cast<float>(posInFrame.x()) / ui->frame->width();

        setProgress(pos);
        emit progressChanged(currIndex);
    }
}

void sliderForm::resizeEvent(QResizeEvent *event)
{
    Q_UNUSED(event);
    updateProgressBar();
    QWidget::resizeEvent(event);
}

void sliderForm::mouseMoveEvent(QMouseEvent *event)
{
    if (movestate && (event->buttons() & Qt::LeftButton)) {
        QPoint posInFrame = ui->frame->mapFromParent(event->pos());
        float pos = static_cast<float>(posInFrame.x()) / ui->frame->width();
        setProgress(pos);
        emit progressChanged(currIndex);
    }
}
